這篇文章是閱讀Asabeneh的30 Days Of Python: Day 10 - Loops後的學習筆記與心得。
Python有兩種迴圈(loop):
while
迴圈如果滿足while
後面的條件,就會執行區域中的程式碼;跟JavaScript(以下簡稱JS)差不多,但條件不用括弧()
包覆,另外是冒號:
及縮排區隔條件與滿足條件執行的程式碼:
count = 0
while count < 5:
print(count)
count += 1
# 印出0到4
跟JS不同的是,Python中可以在滿足while
的條件後,使用else
執行其區域中的程式碼:
count = 0
while count < 5:
print(count)
count += 1
else:
print("count ends in %d" %(count))
# count ends in 5
for
迴圈使用in
遍歷(iterate)可迭代(iterable)的型別,如串列(list)、元組(tuple)、字典(dictionary),以及集合(set)與字串(string)中的項目:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
# prints 1 to 5
在JS中,
in
是遍歷可迭代物件的key,上方程式碼到了JS會印出0到4,要達到相同的輸出,即印出值(value),在JS中要使用of
。
遍歷字典時印出的是鍵(key):
month_days = {
"january": 31,
"febuary": 28,
"march": 31,
"april": 30
}
for key in month_days:
print(key)
# january
# febuary
# march
# april
如果要印出值,可以使用items()
方法轉成字典檢視再遍歷:
month_days = {
"january": 31,
"febuary": 28,
"march": 31,
"april": 30
}
for key, value in month_days.items():
print(key, value)
# january 31
# febuary 28
# march 31
# april 30
與while
迴圈相同,for
迴圈也能使用else
在迴圈結束後執行其區域中的程式碼:
month_days = {
"january": 31,
"febuary": 28,
"march": 31,
"april": 30
}
for key in month_days:
print(key)
else:
print("The first quarter of the year ends")
range
函式Python的for迴圈不像JS的可以加入變數來指明要跑幾次,像是:
for (i = 0; i < 11; i += 1) {
console.log(i);
}
要做到這件事,Python中可以使用range(start, end[, step])
函式,或是再加上list()
、set()
函式轉換成可迭代的物件:
for iterator in range(11):
print(iterator)
# prints 0 to 10
lst = list(range(11))
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
使用break
來中斷進行中的迴圈:
count = 0
while count < 5:
print(count)
count += 1
if count == 3:
break
# prints 0 to 2
month_days = {
"january": 31,
"febuary": 28,
"march": 31,
"april": 30
}
for key in month_days:
if key == "march":
break
print(key)
# january
# febuary
使用continue
來跳過當前迴圈中剩餘未執行的程式碼,進到下一次的迴圈判斷中:
count = 0
while count < 5:
if count == 3:
# 還是要加一,不然會產生無限迴圈
count += 1
continue
print(count)
count += 1
# prints 0, 1, 2, 4
month_days = {
"january": 31,
"febuary": 28,
"march": 31,
"april": 30
}
for key in month_days:
if key == "march":
continue
print(key)
# january
# febuary
# april
使用pass
,運作起來像continue
但語意上是做為暫時的程式運行機制,比方說為了測試else
運作正常,但不想在for
迴圈階段執行其他程式碼:
for key in month_days:
pass
else:
print("The first quarter of the year ends")